//
//  TrainQuery.m
//  MINFOBBS
//
//  Created by juvid on 13-11-28.
//  Copyright (c) 2013年 minfo. All rights reserved.
//

#import "TrainQuery.h"
#import "TrainQueryCell.h"
#import "SBJson.h"
#import "DetectionSystemVersion.h"
#import "MainSearchViewController.h"
#import "UIColor+expanded.h"
#import "TrainTrains.h"
@interface TrainQuery ()

@end

@implementation TrainQuery

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (self.isSelf) {
        
    }
    else{
        
    [self BackButton];
        pageLimit=8;
        pageStart=0;
        loadMore=[[LoadMore alloc]init];
        loadMore.frame= CGRectMake(0, 0, 320, 32);
        [self.tableView addSubview:loadMore];
        self.tableView.showsVerticalScrollIndicator=YES;
        self.tableView.bounces=YES;
        [self GetDatas];
    }
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)BackButton{
    self.navigationItem.titleView=[DetectionSystemVersion SetBarTitle:@"百事搜"];
    [self.navigationItem setHidesBackButton:YES];
    UIButton *btnBack=[[DetectionSystemVersion alloc]BackButton];
    [btnBack addTarget:self action:@selector(BackReturn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem=backItem;
    
}
#pragma mark 导航栏按钮事件
-(void)BackReturn:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillDisappear:(BOOL)animated{
    [tRequest clearDelegatesAndCancel];
    [tRequest cancel];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [NSThread cancelPreviousPerformRequestsWithTarget:self];
}
#pragma mark 异步数据请求
-(void)GetDatas{
    loadMore.loadingTitle.text=@"正在加载...";
    [loadMore.loadingAni startAnimating];
    tRequest=[[[ScreenAccess alloc]init]ASIGetSearch:self.strKey Start:pageStart Limit:pageLimit];
    [tRequest setDelegate:self];
    [tRequest setUsername:@"allMessage"];
    
}
-(void)requestFinished:(ASIHTTPRequest*)request{
    
    NSString *response = [request responseString];
    SBJsonParser * parser = [[SBJsonParser alloc] init];
    NSMutableDictionary *Result = [parser objectWithString:response];
    
    if ([request.username isEqual:@"allMessage"]){
        BOOL IsSuccess=[[[Result objectForKey:@"Response"]objectForKey:@"status"]integerValue]==200?YES:NO;
        if (IsSuccess==YES) {
            if (self.arrReturn==nil) {
                self.arrReturn=[[NSMutableArray alloc]init];
            }
            [self.arrReturn addObjectsFromArray:[[[[[[Result objectForKey:@"Response"] objectForKey:@"Categories"] objectForKey:@"Category"] objectAtIndex:0]objectForKey:@"Items"] objectForKey:@"Item"]];
            loadMore.loadingTitle.text=@"上拉加载更多";
            [loadMore.loadingAni stopAnimating];
            [self.tableView reloadData];
            loadMore.frame=CGRectMake(0, self.tableView.contentSize.height-35, 320, 32);
        }
    }
    else if([request.username isEqual:@"weather"]){
    }
    loadingmore=NO;
    
}

-(void)requestFailed:(ASIHTTPRequest*)request{
    [loadMore.loadingAni stopAnimating];
    loadMore.loadingTitle.text=@"无网络";
    loadingmore=NO;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (self.isSelf) {
        return 1;
        
    }
    else{
        return self.arrReturn.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"TrainQueryCell";
    TrainQueryCell *cell = (TrainQueryCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];

                }
    [[[[[self.arrReturn objectAtIndex:indexPath.row] objectForKey:@"Properties"] objectForKey:@"Property"]objectAtIndex:1] objectForKey:@"text"];
    NSArray *arr=[[[self.arrReturn objectAtIndex:indexPath.row]objectForKey:@"Properties"] objectForKey:@"Property"];
    cell.labTrainTimes.text=[[arr objectAtIndex:0] objectForKey:@"text"];
    cell.imgTrainClass.image=[UIImage imageNamed:[[arr objectAtIndex:1] objectForKey:@"text"]];
    cell.latTotalTime.text=[[arr objectAtIndex:7] objectForKey:@"text"];
    cell.labFirst.text=[[arr objectAtIndex:2] objectForKey:@"text"];
    cell.labTimeFirst.text=[[arr objectAtIndex:3] objectForKey:@"text"];
    cell.labEnd.text=[[arr objectAtIndex:4] objectForKey:@"text"];
    cell.labTimeEnd.text=[[arr objectAtIndex:5] objectForKey:@"text"];
    cell.labTrainClass.text=[[arr objectAtIndex:1] objectForKey:@"text"];
    arr=Nil;
//    cell.textLabel.text=@"string";
    // Configure the cell...
    
    return cell;
}
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100;
}
-(float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 38;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *result;
    result=[[UIView alloc]init];
    result.backgroundColor=[UIColor clearColor];
    if (self.isSelf) {
        UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 3)];
        img.image=[UIImage imageNamed:@"footLine"];
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 3, self.tableView.frame.size.width, 35)];
        [btn setTitle:@"点击查看其他列车班次" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(PrseeMore) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitleColor:[UIColor colorWithHexString:@"0xb7b7b7"] forState:UIControlStateNormal];
        btn.titleLabel.font=[UIFont systemFontOfSize:14];
        [result addSubview:btn];
        [result addSubview:img];
    }
    return result;
}

- (MainSearchViewController *)menuContainerViewController {
    return (MainSearchViewController *)self.parentViewController;
}
-(void)PrseeMore{
    //    if (self.isSelf) {
    TrainQuery *jokecon=[[TrainQuery alloc]init];
    jokecon.strKey=self.strKey;
    [ [self menuContainerViewController].navigationController  pushViewController:jokecon animated:YES];
    //    }
    
    
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    PrevCGPoint=scrollView.contentOffset;
    if (PrevCGPoint.y>scrollView.contentSize.height-scrollView.frame.size.height) {
        if (loadingmore) return;
        loadingmore = YES;
        pageStart++;
        [self GetDatas];
    }
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here, for example:
    // Create the next view controller.
   
    TrainTrains *detailViewController = [[TrainTrains alloc] init];
    NSString *str=[[self.arrReturn objectAtIndex:indexPath.row] objectForKey:@"href"];
    
    //        NSLog(@"%@",str);
    NSRange range = [str rangeOfString:@"query="];
    detailViewController.strKey=[str substringFromIndex:range.location +range.length];
    detailViewController.isSelf=YES;
    str=nil;
//    NSArray *arr=
//    detailViewController.arrReturn=[self.arrReturn objectAtIndex:indexPath.row];
    // Pass the selected object to the new view controller.
    // Push the view controller.
    if (self.isSelf) {
        [ [self menuContainerViewController].navigationController  pushViewController:detailViewController animated:YES];
    }
    else{
        [ self.navigationController  pushViewController:detailViewController animated:YES];
    }
}
 


@end
